package com.link.base.base.common.controller;

import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.model.ScrollImg;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.common.service.ScrollImgService;
import com.link.base.base.product.model.ProdRcmd;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/8 19:14
 */

@Controller
@RequestMapping("/link/scrollImg")
public class ScrollImgController extends BasicController<ScrollImg> {

    @Resource
    private AttachmentService attachmentService;

    @Resource
    private ScrollImgService scrollImgService;

    @Override
    public BasicService<ScrollImg> getBasicService() throws Exception {
        return scrollImgService;
    }

    @Override
    public void beforQueryAllOrExample(ScrollImg entity, HttpServletRequest request) throws Exception {
        super.beforQueryAllOrExample(entity, request);
        String type = request.getParameter("type");
        String activeFlag = request.getParameter("activeFlag");
        if (StringUtils.isNotBlank(type)) {
            entity.setType(type);
        } else {
            throw new ServiceException("系统类型不能为空。");
        }
        if (StringUtils.isNotBlank(activeFlag)) {
            QueryParams qps = new QueryParams();
            qps.addFilter(new Filter("activeFlag", activeFlag));
        }

    }

    /**
     * 更新产品图片
     */
    @RequestMapping(value = "/imgIdUpdate")
    @ResponseBody
    public Map<String, Object> imgIdUpdate(ScrollImg entity, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile myfile = multipartRequest.getFile("myfile");
        String base = "base";
        try {
            if (!checkExistDataCache(base, session, entity)) {
                throw new ServerException("PUBLIC-002");
            }
            if (myfile == null) {
                throw new ServerException("PUBLIC-013");
            }
            ScrollImg oldEntry = scrollImgService.queryById(entity);
            if (oldEntry == null) {
                throw new ServerException("找不到附件");
            }
            try {
                Long oldImgId = oldEntry.getImgId();
                if (null != oldImgId) {
                    Attachment param = new Attachment();
                    param.setId(oldImgId);
                    attachmentService.deleteById(param);
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
            // 插入附件表
            Attachment imgObj = new Attachment();
            imgObj.setHeadId(entity.getId());
            imgObj.setModuleType("HomeScrollImages");
            LCLogger.info().withMessageKey("imgIdUpdate").withMessage("上传附件记录！HeadId:" + entity.getId()).flush();
            // 附件上传
            attachmentService.upload(myfile, imgObj);
            LCLogger.info().withMessageKey("imgIdUpdate").withMessage("插入附件记录！HeadId:" + entity.getId()).flush();
            //向附件表插入附件基础信息
            attachmentService.insert(imgObj);
            entity.setImgId(imgObj.getId());
            scrollImgService.imgIdUpdate(entity);
            //审计追踪新建记录
            ScrollImg newEntry = scrollImgService.queryById(entity);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryAllActive")
    @ResponseBody
    public Map<String, Object> queryAllActive(@JsonParam ScrollImg entity, HttpSession session, HttpServletRequest request,
                                              HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<ScrollImg> list = scrollImgService.queryAllActive(entity);
            result.put("success", true);
            result.put("result", list);
            result.put("count", list.size());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", new ArrayList<ProdRcmd>());
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * @author:yaojiangyi
     * @date :2018-11-16 17:38
     *  更新前操作,将旧的图片在附件删除,更新新的图片
     */
    @Override
    public void beforUpdate(ScrollImg entity, HttpServletRequest request) throws Exception {
        try {
            ScrollImg oldEntry = scrollImgService.queryById(entity);
            if (oldEntry == null) {
                throw new ServerException("PUBLIC-014");
            }
            Long newImgId = entity.getImgId();
            Long oldImgId = oldEntry.getImgId();
            if (!newImgId.equals(oldImgId)) {
                Attachment param = new Attachment();
                param.setId(oldImgId);
                attachmentService.deleteById(param);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new BasicControllerException(e);
        }
    }
}
